package com.googlecode.garbagecan.test.rhino;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import java.util.HashMap;
import java.util.Map;

public class Selection {

	public static void main(String[] args) throws Exception {
		Selection s = new Selection();
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("max", 10);
		attributes.put("njobs", 4);
		System.out.println(s.satisfied1(attributes));
		System.out.println(s.satisfied2(attributes));
		System.out.println(s.satisfied3(attributes));
	}

	public boolean satisfied1(Map<String, Object> attributes) {
		Context cx = Context.enter();

		try {
			Scriptable scope = cx.initStandardObjects();
			scope.put("attributes", scope, attributes);
			String script = "attributes.get(\"max\") == 100 || (attributes.get(\"max\") - attributes.get(\"njobs\") > 5)";
			Object obj = cx.evaluateString(scope, script, "TestScript", 1, null);
			return Boolean.valueOf(obj.toString()).booleanValue();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			Context.exit();
		}
	}

	public boolean satisfied2(Map<String, Object> attributes) {
		Context cx = Context.enter();

		try {
			Scriptable scope = cx.initStandardObjects();
			scope.put("attributes", scope, attributes);
			StringBuffer sb = new StringBuffer();
			for(String key : attributes.keySet()) {
				sb.append(key).append("=").append(attributes.get(key)).append(";");
			}
			sb.append("(max == 100) || (max - njobs > 5)");
			Object obj = cx.evaluateString(scope, sb.toString(), "TestScript", 1, null);
			return Boolean.valueOf(obj.toString()).booleanValue();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			Context.exit();
		}
	}

	public boolean satisfied3(Map<String, Object> attributes) {
		Context cx = Context.enter();

		try {
			Scriptable scope = cx.initStandardObjects();
			//scope.put("attributes", scope, attributes);
			StringBuffer sb = new StringBuffer();
			sb.append("var attributes = {};\n");
			for(String key : attributes.keySet()) {
				sb.append("attributes[\""+key+"\"]").append("=").append(attributes.get(key)).append(";\n");
			}
			sb.append("attributes[\"max\"] == 100 || (attributes[\"max\"] - attributes[\"njobs\"] > 5)");
			Object obj = cx.evaluateString(scope, sb.toString(), "TestScript", 1, null);
			return Boolean.valueOf(obj.toString()).booleanValue();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			Context.exit();
		}
	}
}
